package com.shjn.squirrel.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Process;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.gson.Gson;
import com.shjn.squirrel.bean.httpBean.AppCrashReq;
import com.shjn.squirrel.utils.OkhttpHelper;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 用来处理App崩溃的服务
 */
public class AppCrashService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //提取崩溃参数
        String deviceID = intent.getStringExtra("deviceID");
        String errorLog = intent.getStringExtra("errorLog");
        //将崩溃信息上传到服务器
        postCrashInfo(deviceID, errorLog);
        //2秒后，杀死服务进程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                stopSelf();
                Process.killProcess(Process.myPid());
            }
        }).start();
        //杀死后不重启
        return START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 上传错误信息到服务器
     */
    private static void postCrashInfo(String deviceID, String crashInfo) {
        OkhttpHelper.postRequest("http://8.210.32.7/squirrelWebDemo/appCrashServlet",
                new Gson().toJson(new AppCrashReq(deviceID, crashInfo)),
                new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("info", "appCrash_onFailure: " + e.getMessage());

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i("info", "appCrash_response: " + response.body().string());
                    }
                });
    }
}
